package com.fjnu.controller;

import com.fjnu.domain.dto.UserConditionDto;
import com.fjnu.domain.dto.UserDto;
import com.fjnu.domain.entity.User;
import com.fjnu.domain.vo.ResponseResult;
import com.fjnu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/blog-api/v0.1/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/list")
    public ResponseResult<List<User>> list(@RequestBody UserConditionDto userCond) {
        // 参数验证
        if (userCond == null) {
            throw new IllegalArgumentException("查询条件不能为空");
        }

        var pageResult = userService.queryUsers(userCond, 1, 10);

        if (pageResult == null) {
            throw new RuntimeException("查询服务返回空结果");
        }

        if (pageResult.getData() == null || pageResult.getData().isEmpty()) {
            return ResponseResult.success("查询成功，但未找到匹配的用户", Collections.emptyList());
        }

        return ResponseResult.success(pageResult.getData());
    }

    @PostMapping("/add")
    public ResponseResult<String> add(@RequestBody UserDto userDto) {
        User user = new User();
        user.setName(userDto.getUsername());
        user.setPassword(userDto.getPassword());
        user.setEmail(userDto.getEmail());
        user.setGender(userDto.getGender());

        int result = userService.register(user);
        if (result > 0) {
            return ResponseResult.success("用户添加成功");
        }
        return ResponseResult.error("用户添加失败");
    }

    @PostMapping("/password/change")
    public ResponseResult<String> changePassword(@RequestParam String userId, @RequestParam String newPassword) {
        int result = userService.updatePassword(Integer.parseInt(userId), newPassword);
        if (result > 0) {
            return ResponseResult.success("密码修改成功");
        }
        return ResponseResult.error("密码修改失败");
    }
}